package com.example.utils;

import com.example.entity.ResponseBean;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class ExceptionController {

	// 捕捉shiro的异常
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(ShiroException.class)
	public ResponseBean handle401(ShiroException e) {
		//请求头没有携带token会走这里.
		//没权限也会走这里
		return new ResponseBean(401, e.getMessage(), null);
	}

	// 捕捉UnauthorizedException
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(UnauthorizedException.class)
	public ResponseBean handle401() {
		return new ResponseBean(401, "Unauthorized", null);
	}

	// 捕捉其他所有异常
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ResponseBean globalException(HttpServletRequest request, Throwable ex) {
		return new ResponseBean(getStatus(request).value(), ex.getMessage(), null);
	}

	private HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return HttpStatus.valueOf(statusCode);
	}


	@ExceptionHandler(AuthenticationException.class)
	public Object AuthenticationException(AuthenticationException e) {

		e.printStackTrace();

		/*String callback = request.getParameter("callback");
		System.out.println(callback);
		return JsonUtils.toJSONString(callback, new JsonUtils(e));*/
		return new JsonResult(e);
	}

	@ExceptionHandler(ExceptionUtil.class)
	public Object handleException(ExceptionUtil e) {

		e.printStackTrace();

		/*String callback = request.getParameter("callback");
		System.out.println(callback);
		return JsonUtils.toJSONString(callback, new JsonUtils(e));*/
		return new JsonResult(e);
	}
}